<?
// /ui/commandhandler/request/group|renew|restore/group/[groupname][/status/ok]

class News_Command_ArticleReader
{
    var $Controller;
    var $Group; 
    var $Index;
    var $Item;
    var $Page;
    function News_Command_ArticleReader($controller)
	{
	    $this->Controller = $controller;
        $this->Group      = $this->Controller->Settings['group']; 
        $this->Index      = $this->Controller->Settings['index']; 
        $this->Item       = $this->Controller->Settings['item']; 
        $this->Seek       = $this->Controller->Settings['seek'];
        $this->Page       = $this->Controller->Settings['page'];
        $this->Path       = "notify/{$this->Group}.{$this->Index}.index";
        $this->URI        = $this->Controller->URI (array('status'=>'ok'));
	}
	
	function GetURI()
	{
	    $uri = $this->Controller->URI (array('ui'=>'articlelist', 'request'=>NULL));
		if (isset($this->Controller->Settings['response']))
		{ 
		    $uri = "/x/groupname/{$this->Group}/pageindex/{$this->Page}/index/{$this->Index}/item/{$this->Item}";	
		}
	    return array("RequestURI"  => $this->URI,
	                 "RedirectURI" => $uri);
	}
	
	function GetStatus()
	{
	    if (!file_exists($this->Path))
        {
            return 'OK';
        } 
        return '';
	}
	
	function Signal()
	{   
        $message =  "{$this->Group}?{$this->Item}";
        
        if (strlen($this->Controller->Settings['seek']) > 0)
        {
            $message = "pageitem={$this->Item}&groupname={$this->Group}&filename=data/find/{$this->Group}/{$this->Seek}.xml";
        } 
        if (strlen($this->Controller->Settings['status']) > 0)
        {
            return $this->GetStatus ();
        } 
        
        $this->Controller->Save($this->Path, $message); 
        return $this->Controller->Dialog ($this->GetURI());
	}
	
	function Invoke($command)
	{  
	
	    $this->Path = $command['path']; 
        $array     = explode ('?', $this->Controller->Read($command['path'])); 
        $groupname = $array[0]; 
        $pageitem  = $array[1]; 
        $filename  = "data/{$groupname}.xml"; 
		if (strpos($groupname, '&')) parse_str($groupname);
		
		
        $ids       = explode ('-', $pageitem);
        $key       = $ids[0];
        $idx       = "data/tube/{$groupname}/{$key}.idx";
        $pageindex = $command['arg1'];
		if (file_exists($idx) || $this->Controller->Queue->Recall($pageitem))
        {
		    unlink ($this->Path);
		    return;
        }
		$this->Controller->LogEntry ("Loading article {$pageitem}", 1, 1, $groupname); 
		
        if (file_exists($filename)) 
        {
		    $xml     = simplexml_load_file($filename);
		    $parent  = $xml->xpath("//list/article[@index='{$pageindex}']");
		    $result  = $xml->xpath("//list/article[@index='{$pageindex}']/items/article[contains(id, '{$pageitem}')]"); 
		    $nodeid  = $result[0]->id;
		    $type    = $parent[0]->type;
		    
		    if ($type=='rar')
		    {  
		        $rars  = $xml->xpath("//list/article[@index='{$pageindex}']"); 
		        $this->Controller->Queue->ReadRar($nodeid, $pageindex, $groupname, $rars[0]->subject);
		        $this->Controller->Queue->Start();
		        unlink ($this->Path);
		        return;
		    } 
		    
			$check   = (!isset($type)) || $type=='' || $type=='picture';
		    $picname = $this->Controller->GetArticle ($groupname, $result[0]->id,$check?NULL : "data/temp/{$groupname}", $check);
		    
		    if (!file_exists($picname))
		    {
		        unlink ($this->Path);
		        return;
		    }
		    
		    $subject = $result[0]->subject;
		    $arr     = explode ('.', $picname);
		    $ext     = array_pop($arr); 
		    $message = "Article loaded {$picname}";
		    $encode  = false;
		    
//		    unencoded video
		    if ($ext != 'flv' && $ext != 'm4v' && $type != 'm4v' && !$check)
		    {
		        $this->Controller->LogEntry ("Adding to queue...", 65, 100, $groupname);
		        $this->Controller->Queue->Read($picname, $nodeid, $groupname, $subject);   
		        $this->Controller->Queue->Start(); 
		        $encode = true;
		    } 
		    
		    if (!$check)
		    {
		        $jpeg = "{$picname}.jpeg";
		        if (!file_exists($jpeg) && !$encode)
		        {
		            $frame   = $this->VideoFrame ($picname);
		            $message = "Conversion succeeded {$picname}"; 
		        }
		        
		        if (file_exists($picname) && !$encode)
		        { 
		            echo "Checking for index...\n";
		            if (!file_exists($idx))
		            {
		                echo "Creating index...\n";
		                $dir = "data/tube/{$groupname}";
		                $dur  = $this->Controller->Queue->GetDuration($picname); 
		                $this->Controller->Queue->CreateIndex($dir, $key, $subject, $picname, $dur, $jpeg);
		            }
		        }
		    }
		    
		    $this->Controller->LogEntry ($message, 1, 1, $groupname);
		    echo "$picname\n"; 
		    unlink ($this->Path);
		    return;
        }   
        echo "Could not find group file {$filename}\n";
	}

//    function run_in_background($Command, $Priority = 0)
//    {
//        unlink ('command.out');
//        if($Priority)
//            $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
//        else
//            $PID = shell_exec("nohup $Command > /var/www/html/command.out & echo $!");
//        return($PID);
//    }
//    
//    function VideoEncode ($path)
//    { 
//        $output = $path . '.m4v';
//        echo "Preparing to encode {$path}\n------------------------------\n";
//        $command = "ffmpeg -i \"{$path}\" -f mp4 -vcodec libx264 -vpre default " .
//                   "-bufsize 1835k -acodec libfaac " .
//                   "-b 400k \"{$output}\"";
//        echo "Sending {$command}\n------------------------------\n";
////        passthru($command);
//        $pid = $this->run_in_background($command);
//        return $pid;
//    }
    
    function VideoFrame($path)
    {
        $output = $path . '.jpeg';
        $c=("ffmpeg -i \"{$path}\" -vcodec mjpeg -vframes 1 -ss 15 -an -f rawvideo -s 320x240 \"{$output}\"");
        passthru($c);
        return $output;
    }
}



